package top.yangyitao.service.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import top.yangyitao.dao.RoleRepository;
import top.yangyitao.entity.Role;
import top.yangyitao.service.RoleService;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleRepository roleDao;
	@Override
	public Role getOne(long id) {
		return roleDao.findById(id).get();
	}

	@Override
	public List<Role> findAll() {
		return roleDao.findAll();
	}

	@Override
	public void save(Role role) {
		roleDao.saveAndFlush(role);
	}

	@Override
	public void save(List<Role> roles) {
		roleDao.saveAll(roles);
		roleDao.flush();
	}

	@Override
	public void delete(Role role) {
		roleDao.delete(role);
	}

	@Override
	public void delete(List<Role> roles) {
		roleDao.deleteAll(roles);
	}

	@Override
	public List<Role> findAllById(List<Long> ids) {
		return roleDao.findAllById(ids);
	}

	@Override
	public Role findByName(String name) {
		return roleDao.findByName(name);
	}

	@Override
	public Role findByStringRole(String stringRole) {
		return roleDao.findByStringRole(stringRole);
	}

	@Override
	public List<Role> findAllExceptSA() {
		Sort sort = new Sort(Sort.Direction.ASC,"id");
		Specification<Role> spec = new Specification<Role>() {

			@Override
			public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				return criteriaBuilder.notEqual(root.get("stringRole"), "superAdmin");
			}
			
		};
		return roleDao.findAll(spec, sort);
	}

}
